<?php namespace App\Http\Controllers\Oauth;

use Illuminate\Routing\Controller as BaseController;
use App\Services\Oauth\Login\Process as LoginProcess;
use App\Services\Oauth\Reg\Process as RegProcess;
use App\Models\Oauth\Members as MembersModel;
use App\Services\Oauth\SC;
use Authorizer, Request, Input, Redirect, Response, Lang;

/**
 * 处理oauth 授权相关
 *
 * @author jiang <mylampblog@163.com>
 */
class AuthorizeController extends BaseController
{
    /**
     * oauth process
     * 
     * @var object
     */
    private $loginProcess;

    /**
     * oauth process
     * 
     * @var object
     */
    private $regProcess;

    /**
     * 授权的时候是否需要确认
     * 
     * @var boolean
     */
    private $isNeedApply = false;

    /**
     * 初始化
     */
    public function __construct()
    {
        $this->loginProcess = new LoginProcess();
        $this->regProcess = new RegProcess();
    }

    /**
     * 处理登陆和授权
     */
    public function authorize()
    {
        if( ! $this->loginProcess->hasLogin()) return view('oauth.login', compact('params'));
        if($this->isNeedApply) {
            return $this->needApply();
        }
        return $this->noNeedApply();
    }

    /**
     * 需要确认的话显示确认界面
     */
    private function needApply()
    {
        $authParams = Authorizer::getAuthCodeRequestParams();
        $formParams = array_except($authParams, 'client');
        $formParams['client_id'] = $authParams['client']->getId();
        return view('oauth.authorization-form',
            ['params' => $formParams,'client' => $authParams['client']
        ]);
    }

    /**
     * 需要用户确认的情况下会Post到这里处理
     */
    public function postAuthorize()
    {
        if( ! $this->loginProcess->hasLogin()) return false;
        $params = Authorizer::getAuthCodeRequestParams();
        $userInfo = SC::getLoginSession();
        $params['user_id'] = $userInfo['id'];
        $redirectUri = '';
        if (Input::get('approve') !== null) {
            $redirectUri = Authorizer::issueAuthCode('user', $params['user_id'], $params);
        }
        if (Input::get('deny') !== null) {
            $redirectUri = Authorizer::authCodeRequestDeniedRedirectUri();
        }
        return Redirect::to($redirectUri);
    }

    /**
     * 不需要用户确认，直接返回
     */
    private function noNeedApply()
    {
        $params = Authorizer::getAuthCodeRequestParams();
        $userInfo = SC::getLoginSession();
        $params['user_id'] = $userInfo['id'];
        $redirectUri = Authorizer::issueAuthCode('user', $params['user_id'], $params);
        return Redirect::to($redirectUri);
    }

    /**
     * 开始登录处理
     */
    public function proc()
    {
        $username = Request::input('username');
        $password = Request::input('password');
        $callback = Request::input('callback');

        if($error = $this->loginProcess->validate($username, $password)) {
            return response()->json(['msg' => $error, 'result' => false])->setCallback($callback);
        }

        $userInfo = $this->loginProcess->check($username, $password);

        $success = ['msg' => '登录成功', 'result' => true];
        $error = ['msg' => '登录失败', 'result' => false];
        $result = $userInfo ? $success : $error;
        
        return response()->json($result)->setCallback($callback);
    }

    /**
     * 初始化登录，返回加密密钥
     */
    public function prelogin()
    {
        return response()->json([
            'pKey' => $this->loginProcess->setPublicKey(),
            'a' => csrf_token()
        ])->setCallback(Request::input('callback'));
    }

    /**
     * 认证成功后返回用户的信息
     */
    public function userDetail()
    {
        $userId = Authorizer::getResourceOwnerId();
        $userInfo = with(new MembersModel())->getOneUserById($userId);
        $return['id'] = $userInfo['id'];
        $return['name'] = $userInfo['name'];
        $return['realname'] = $userInfo['realname'];
        $return['mobile'] = $userInfo['mobile'];
        return Response::json($return);
    }

    /**
     * regdo
     */
    public function regDo()
    {
        $username = Request::input('username');
        $password = Request::input('password');
        $password_confirm = Request::input('password_confirm');
        $realname = Request::input('realname');
        $callback = Request::input('callback');

        if( ! $this->regProcess->validate($username, $password, $password_confirm, $realname )) {
            $result = ['msg' => $this->regProcess->getErrorMessage(), 'result' => false];
            return response()->json($result)->setCallback($callback);
        }

        if( ! $this->regProcess->addUser($username, $password, $realname) ) {
            $result = ['msg' => $this->regProcess->getErrorMessage(), 'result' => false];
            return response()->json($result)->setCallback($callback);
        }

        $result = ['msg' => Lang::get('reg.reg_success'), 'result' => true];

        return response()->json($result)->setCallback($callback);
    }

    /**
     * 注册用户
     */
    public function reg()
    {
        $redirectUri = urldecode(Request::input('redirectUri'));
        return view('oauth.reg', compact('redirectUri'));
    }

}